package com.exam.serviceimpl;

import com.exam.entity.PaperManage;
import com.exam.exceptions.MyCustomException;
import com.exam.mapper.PaperMapper;
import com.exam.mapper.ScoreMapper;
import com.exam.service.PaperService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class PaperServiceImpl implements PaperService {

    @Autowired
    private PaperMapper paperMapper;
    @Autowired
    private ScoreMapper scoreMapper;
    @Override
    public List<PaperManage> findAll() {
        return paperMapper.findAll();
    }

    @Override
    public List<PaperManage> findById(Integer paperId) {
        return paperMapper.findById(paperId);
    }

    @Override
    public int add(PaperManage paperManage) {
        return paperMapper.add(paperManage);
    }

    @Override
    public int findPaperIdByExamCode(Integer examCode) {
        return paperMapper.findPaperIdByExamCode(examCode);
    }

    @Override
    public String findExamTimeByPaperId(Integer paperId) {
        String examData = paperMapper.findExamTimeByPaperId(paperId);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date parse=null;
        try {
            parse = sdf.parse(examData);
        } catch (ParseException e) {
            System.out.println("日期转换错误");
        }
        Date currentData = new Date();
        //将当前日期类型转换为String类型
        String currentDataStr = sdf.format(currentData);
        if(currentDataStr.equals(examData)){
            return null;
        }
        //如果考试大于当前时间，则考试还没开始
        if(currentData.getTime()<parse.getTime()){
            throw new MyCustomException("考试还没开始");
        }else if(currentData.getTime()>parse.getTime()) {
            //如果考试时间小于当前时间，则考试已经结束
            throw new MyCustomException("考试已经结束");
        }
        return null;
    }

    @Override
    public int findPaperRow(Integer examCode, Integer studentId) {
        int row = scoreMapper.findPaperRow(examCode, studentId);
        if(row!=0){
            throw new MyCustomException("你已经参加过该考试");
        }
        return 0;
    }
}
